package cn.lijiajia3515.cairo.system.modules.area;

import cn.lijiajia3515.cairo.system.modules.SystemMongoConstants;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class AreaService {
	private final MongoTemplate mongoTemplate;

	public AreaService(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	@Cacheable("area:subs")
	public List<AreaTree> subs(String id) {
		return mongoTemplate.find(Query.query(Criteria.where(AreaMongo.FIELD.PARENT).is(id)), AreaMongo.class, SystemMongoConstants.Collection.AREA)
			.stream()
			.map(AreaConverter::areaTree)
			.collect(Collectors.toList());
	}

	public List<Area> find(FindAreaParam param) {
		return param.getIds().stream().flatMap(x -> findById(x, param.getExtension()).stream()).collect(Collectors.toList());
	}

	@Cacheable("area:id")
	public Optional<Area> findById(String id, Map<String, String> extension) {
		return Optional.ofNullable(mongoTemplate.findOne(Query.query(Criteria.where(AreaMongo.FIELD.ID).is(id)), AreaMongo.class, SystemMongoConstants.Collection.AREA))
			.map(x -> AreaConverter.area(x, extension));
	}
}
